package com.javatest2;

import java.util.Scanner;

/**
 * @program: item_02
 * @description: 描述
 * 在二叉树中寻找值最大的节点并返回。
 * 示例
 * 样例1:
 * 输入:
 * {1,-5,3,1,2,-4,-5}
 * 输出: 3
 * 说明:
 * 这棵树如下所示：
 * 1
 * / \
 * -5 3
 * / \ / \
 * 1 2 -4 -5
 * 样例 2
 * 2021/2/3 题目
 * https://share.jiuzhang.com/problem?id=632 2/2
 * 输入:
 * {10,-5,2,0,3,-4,-5}
 * 输出: 10
 * 说明:
 * 这棵树如下所示：
 * 10
 * / \
 * -5 2
 * / \ / \
 * 0 3 -4 -5
 * @author: LL
 * @create: 2021-02-02 18:24
 */
public class Subject12 {

    private TreeNode maxNode;

    public TreeNode maxNode(final TreeNode root) {
        // write your code here
        if (root == null) {
            return null;
        }
        traverse(root);
        return this.maxNode;
    }

    private void traverse(final TreeNode root) {
        if (root == null) {
            return;
        }
        if (this.maxNode == null || this.maxNode.getVal() < root.getVal()) {
            this.maxNode = root;
        }
        if (root.getLeft() != null) {
            traverse(root.getLeft());
        }
        if (root.getRight() != null) {
            traverse(root.getRight());
        }
    }

    public static TreeNode preCreat(TreeNode btNode) {
        final Scanner in = new Scanner(System.in);
        System.out.println("输入结点的值");
        final int value = in.nextInt();
        if (value != 0) {
            btNode = new TreeNode();
            btNode.setVal(value);
            //以下两行是核心代码
            btNode.setLeft(preCreat(btNode.getLeft()));
            btNode.setRight(preCreat(btNode.getRight()));
        } else {
            //这个是一定要有的，确定最终的结束结点
            btNode = null;
        }
        return btNode;
    }

    public static void main(final String[] args) {
        final TreeNode treeNode = new TreeNode();
        final TreeNode treeNode1 = preCreat(treeNode);
        final Subject12 subject12 = new Subject12();
        final TreeNode treeNode2 = subject12.maxNode(treeNode1);
        System.out.println(treeNode2.getVal());

    }
}

class TreeNode {
    private int val;
    private TreeNode left, right;

    public int getVal() {
        return this.val;
    }

    public void setVal(final int val) {
        this.val = val;
    }

    public TreeNode getLeft() {
        return this.left;
    }

    public void setLeft(final TreeNode left) {
        this.left = left;
    }

    public TreeNode getRight() {
        return this.right;
    }

    public void setRight(final TreeNode right) {
        this.right = right;
    }

    public TreeNode() {
    }

    public TreeNode(final int val) {
        this.val = val;
        this.left = this.right = null;
    }
}
